/*
 * Lock.cpp
 *
 *  Created on: 2023年12月22日
 *      Author: Admin
 */
#include "Lock.h"
#include "utils/BrightnessHelper.h"
#include "entry/EasyUIContext.h"
#include "storage/StoragePreferences.h"
#include "utils/Log.h"
#include "uart/ProtocolCustom.h"
int SCREEN_LOCK_TIME = 60; //默认60s锁屏
#define SCREEN_OFF_TIME 60  //60s屏幕熄屏

// 需要打印锁屏时间时，打开以下宏
//#define DEBUG_LOCK_TIME

Lock::Lock()
{   
    _lock_count = 0;
    _screen_off_count = 0;
    _status = E_LOCK_STATUS_UNLOCKED;
    _is_lock_open = true;
    _is_lock_count = true;
}

Lock::~Lock()
{
}

Lock* Lock::getInstance() {
    static Lock instance;
    return &instance;
}

void Lock::lock(bool screen_off) {
    EASYUICONTEXT->openActivity("lockActivity");
    _status = E_LOCK_STATUS_LOCKED;
    if(screen_off){
        screenOff();
    }
}

void Lock::unlock() {
    EASYUICONTEXT->closeActivity("lockActivity");
    _status = E_LOCK_STATUS_UNLOCKED;
}    

void Lock::screenOff() {
    BRIGHTNESSHELPER->backlightOff();
    _status = E_LOCK_STATUS_SCREEN_OFF;
}
void Lock::screenOn() {
    BRIGHTNESSHELPER->backlightOn();
    if(_is_lock_open) {
    	if(strcmp(EASYUICONTEXT->currentAppName(), "lockActivity") == 0) {
    		_status = E_LOCK_STATUS_LOCKED;
    	}else{
    		_status = E_LOCK_STATUS_UNLOCKED;
    	}
    }else {
    	_status = E_LOCK_STATUS_UNLOCKED;
    }
}

void Lock::reset() {
#ifdef DEBUG_LOCK_TIME
	LOGD("reset--------\n");
#endif
    _lock_count = 0;
    _screen_off_count = 0;
}   

E_LOCK_STATUS Lock::getStatus() const{
    return _status;
}

void Lock::timeRun() {
	if(_is_lock_count && _status == E_LOCK_STATUS_UNLOCKED){
#ifdef DEBUG_LOCK_TIME
		LOGD("_lock_count: %d", _lock_count);
#endif
		_lock_count++;
		if(_lock_count > SCREEN_LOCK_TIME){
			if(_is_lock_open){
				lock();
				protocol::ledControl(false);	//关闭led灯
			}
		}
	}
//到60s锁没开就直接熄屏
	if((_status == E_LOCK_STATUS_LOCKED || !_is_lock_open) && _status != E_LOCK_STATUS_SCREEN_OFF){
#ifdef DEBUG_LOCK_TIME
		LOGD("_screen_off_count: %d", _screen_off_count);
#endif
		++_screen_off_count;
		if(_screen_off_count > SCREEN_OFF_TIME) {
			screenOff();
			protocol::ledControl(false);	//关闭led灯
		}
	}
}   

void Lock::setLockOpen(bool is_open) {
    _is_lock_open = is_open;
}

bool Lock::getLockOpen() const {
	return _is_lock_open;
}

void Lock::set_auto_count(bool isCount){
	_is_lock_count = isCount;
	reset();
}
